<?php
/**
 * Description of AppConfig
 *
 * @author Alexey
 */
require_once APPLICATION_PATH . '/components/Environment.php';

class AppConfig {

    const CONFIG_DIR = "/config";
    private $_config;
    private $_envConfig;
    private $_env;
    
    public function __construct()
    {
        $this->_env       = new Environment();
        $this->_config    = $this->getBaseConfig();
        $this->_envConfig = $this->getEnvironmentConfig();
        if ($this->_envConfig)
        {
            $this->_config = $this->mergeConfigs($this->_config, $this->_envConfig);
        }
    }

    protected function getEnvironmentConfig()
    {
        $envConfig = array();
        if ($this->_env->getEnvConfigFile())
        {
            $envConfig = require($this->_env->getEnvConfigFile());
        }
        return $envConfig;
    }

    protected function mergeConfigs(array $config1, array $config2)
    {
        foreach($config2 as $key => $value)
        {
            if (array_key_exists($key, $config1) && is_array($value))
            {
                $config1[$key] = $this->mergeConfigs($config1[$key], $config2[$key]);
            }
            else
            {
                $config1[$key] = $value;
            }
        }
        return $config1;
    }

    protected function getBaseConfig()
    {
         return require(AppConfig::getConfigDir() . "/main.php");
    }

    public function getConfig()
    {
        return $this->_config;
    }

    public static function getConfigDir()
    {
        return APPLICATION_PATH . AppConfig::CONFIG_DIR;
    }
    
}
?>